package com.kye.express.business.order_detail;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewAfterTextChangeEvent;
import com.kennyc.bottomsheet.BottomSheet;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.utils.GsonUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.map.MapUtils;
import com.kye.express.business.order_detail.viewbinder.OrderStatusRouterViewBinder;
import com.kye.express.business.score.ScoreActivity;
import com.kye.express.databinding.ActivityOrderDetailBinding;
import com.kye.express.databinding.BottomSheetOrderStatusProgressRouterBinding;
import com.kye.express.utils.ClipboardUtils;
import com.kye.express.utils.DrawableUtils;
import com.kye.express.utils.PhoneUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.AppDatabase;
import com.kye.model.bean.dstance.DstanceBean;
import com.kye.model.bean.logistics.LogisticsDriverInfoBean;
import com.kye.model.bean.logistics.LogisticsUrgeResultBean;
import com.kye.model.bean.order.OrderDetailResultBean;
import com.kye.model.bean.order.OrderStatusBean;
import com.kye.model.bean.order.UrgeRecordBean;
import com.kye.model.bean.user.User;
import com.kye.base.Logger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * test
 */
public class OrderDetailActivity extends BaseAppCompatActivity implements OrderDetailContract.OrderDetailView {

    private static final String TAG_ORDER_PHONE = "TAG_ORDER_PHONE";
    private static final String TAG_ORDER_CODE = "TAG_ORDER_CODE";
    private static final String TAG_ORDER_SCORE_CODE = "TAG_ORDER_SCORE_CODE";
    private static final String TAG_USER_INFO = "TAG_USER_INFO";
    private static final String TAG_ORDER_STATUS_PROGRESS = "TAG_ORDER_STATUS_PROGRESS";

    private ActivityOrderDetailBinding binding;
    private OrderDetailContract.OrderDetailPresenter presenter;
    private String phone;
    private String orderCode;
    private String scoreCode;
    private User userInfo;
    private OrderDetailResultBean orderDetailResultBean;
    private ArrayList<OrderStatusBean> orderStatusBeans;
    private Dialog dialog;
    private MultiTypeAdapter orderStatusAdapter;
    private BottomSheet bottomSheet;
    private MaterialDialog showUrgeSuccessDialog;
    private MaterialDialog showUrgeMessageDialog;
    private MaterialDialog showOrderCancelDialog;
    private Disposable subscribeMessageInput;
    private String urgeMessage;
    private BaiduMap mMap;
    private final int REQUEST_CODE_SCORE = 1000;
    private Marker mCarMarker;
    private Polyline mPolyline;
    private LatLng mCustomLatLng;
    private Marker mCarPopMarker;

    /**
     * 订单跳转Intent
     * @param context
     * @param phone
     * @param orderCode
     * @param scoreCode
     *      1.如果是从订单列表跳转，从列表item中传scoreCode
     *      2.如果是下单成功后跳转，scoreCode默认传 "5"
     * @return
     */
    public static Intent newStartIntent(Context context, String phone, String orderCode, String scoreCode) {
        Intent intent = new Intent(context, OrderDetailActivity.class);
        intent.putExtra(TAG_ORDER_PHONE, phone);
        intent.putExtra(TAG_ORDER_CODE, orderCode);
        intent.putExtra(TAG_ORDER_SCORE_CODE, scoreCode);
        return intent;
    }

    public static Intent newStartIntentForNewTask(Context context, String phone, String orderCode, String scoreCode) {
        Intent intent = new Intent(context, OrderDetailActivity.class);
        intent.putExtra(TAG_ORDER_PHONE, phone);
        intent.putExtra(TAG_ORDER_CODE, orderCode);
        intent.putExtra(TAG_ORDER_SCORE_CODE, scoreCode);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_order_detail);
        presenter = new OrderDetailContract.OrderDetailPresenter();
        if (savedInstanceState == null) {
            phone = getIntent().getStringExtra(TAG_ORDER_PHONE);
            orderCode = getIntent().getStringExtra(TAG_ORDER_CODE);
            scoreCode = getIntent().getStringExtra(TAG_ORDER_SCORE_CODE);
        } else {
            phone = savedInstanceState.getString(TAG_ORDER_PHONE);
            orderCode = savedInstanceState.getString(TAG_ORDER_CODE);
            scoreCode = savedInstanceState.getString(TAG_ORDER_SCORE_CODE);
            orderStatusBeans = savedInstanceState.getParcelableArrayList(TAG_ORDER_STATUS_PROGRESS);
        }
        initToolbar(savedInstanceState);
        initViews(savedInstanceState);
        initEvents(savedInstanceState);
        initData(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(TAG_ORDER_PHONE, phone);
        outState.putString(TAG_ORDER_CODE, orderCode);
        outState.putString(TAG_ORDER_SCORE_CODE, scoreCode);
        outState.putParcelableArrayList(TAG_ORDER_STATUS_PROGRESS, orderStatusBeans);
        super.onSaveInstanceState(outState);
    }

    private void initToolbar(Bundle savedInstanceState) {
        setSupportActionBar(binding.toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        binding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initViews(Bundle savedInstanceState) {
        mMap = binding.mapView.getMap();
        mMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
    }

    private void initEvents(Bundle savedInstanceState) {
        RxView.clicks(binding.llErrorNetCustom.btErrorNetRetry)
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorServerCustom.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.orderGoodsStateContainer)
                .compose(new DebounceObservableTransformer<Object>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        // 查看状态路由
                        presenter.getOrderStatusProgress(orderDetailResultBean, userInfo);
                    }
                });
        RxView.clicks(binding.buttonUrge)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        presenter.postOrderUrge(orderCode, userInfo);
                    }
                });
        RxView.clicks(binding.buttonScore)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Intent intent = ScoreActivity.newStartIntentForScoreOrder(OrderDetailActivity.this, orderDetailResultBean.getOrderMain().getOrderCode());
                        startActivityForResult(intent, 0);
                    }
                });
        RxView.clicks(binding.orderEdit)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Logger.d("orderEdit");

                    }
                });
        RxView.clicks(binding.orderCancel)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Logger.d("orderCancel");
                        showOrderCancelDialog();
                    }
                });
        RxView.clicks(binding.callDriver)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {

                    private MaterialDialog mDialog;

                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * todo : 拨打取件司机电话
                         */
                        if (mDialog == null) {
                            mDialog = new MaterialDialog.Builder(OrderDetailActivity.this)
                                    .title("温馨提示")
                                    .content("是否拨打取件司机电话")
                                    .positiveText("确认拨打")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            /**
                                             * todo : 缺失字段
                                             */
                                            LogisticsDriverInfoBean driverInfo = binding.getDirverInfo();
                                            if (driverInfo != null) {
                                                PhoneUtils.call(OrderDetailActivity.this, driverInfo.getTel());
                                            }
                                        }
                                    })
                                    .build();
                        }
                        mDialog.show();
                    }
                });
        RxView.clicks(binding.helpToCall)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {

                    private MaterialDialog mDialog;

                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * todo : 联系跨越专员
                         */
                        if (mDialog == null) {
                            mDialog = new MaterialDialog.Builder(OrderDetailActivity.this)
                                    .title("温馨提示")
                                    .content("是否拨打跨越专员电话")
                                    .positiveText("确认拨打")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            PhoneUtils.call(OrderDetailActivity.this, "13500000000");
                                        }
                                    })
                                    .build();
                        }
                        mDialog.show();
                    }
                });
        RxView.clicks(binding.helpToCall24Hour)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {

                    private MaterialDialog mDialog;

                    @Override
                    public void accept(Object o) throws Exception {
                        /**
                         * todo : 联系24小时客服
                         */
                        if (mDialog == null) {
                            mDialog = new MaterialDialog.Builder(OrderDetailActivity.this)
                                    .title("温馨提示")
                                    .content("是否拨打24小时客服电话")
                                    .positiveText("确认拨打")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            PhoneUtils.call(OrderDetailActivity.this, "4008-098-098");
                                        }
                                    })
                                    .build();
                        }
                        mDialog.show();
                    }
                });
        RxView.clicks(binding.copyOrderCode)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        ClipboardUtils.copy(binding.orderCode.getText().toString(), OrderDetailActivity.this);
                        ToastManager.show(OrderDetailActivity.this, "复制成功");
                    }
                });
    }

    private void initData(Bundle savedInstanceState) {
        binding.statusLayout.showLoadingView();
        presenter.bind(this);
        presenter.initLBSTraceClient(this);
        setResult(Activity.RESULT_CANCELED);
    }

    @Override
    public void onUser(User user) {
        userInfo = user;
        if (user.isLogin()) {
            phone = user.getPhone();
            binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
                @Override
                public void onLoading() {
                    presenter.getOrderDetail(phone, orderCode, scoreCode, user);
                }
            });
            presenter.getOrderDetail(phone, orderCode, scoreCode, user);
        } else {
            ToastManager.showCenterForShort("请先登录");
            finish();
        }
    }

    private void initUrgeOption(String code) {
        // 催件显示
        Single.just(code)
                .map(new Function<String, UrgeRecordBean>() {
                    @Override
                    public UrgeRecordBean apply(String code) throws Exception {
                        UrgeRecordBean query = AppDatabase.getInstance(getApplicationContext()).urgeRecordDao()
                                .query(code);
                        if (query == null) {
                            return new UrgeRecordBean();
                        }
                        return query;
                    }
                })
                .map(new Function<UrgeRecordBean, Boolean>() {
                    @Override
                    public Boolean apply(UrgeRecordBean urgeRecordBean) throws Exception {
                        /**
                         * 10分钟内不可以重复催单
                         */
                        Date now = new Date();
                        long time = now.getTime();
                        return (time - urgeRecordBean.getTime() - 60 * 1000 * 10) > 0;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(Boolean canUrge) {
                        // true可以再次催件
                        if (canUrge) {
                            binding.buttonUrge.setVisibility(View.VISIBLE);
                        } else {
                            binding.buttonUrgeDone.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                });
    }

    @Override
    public void getOrderDetailSuccess(OrderDetailResultBean orderDetailResultBean) {
        this.orderDetailResultBean = orderDetailResultBean;
        binding.statusLayout.showContentView();
        binding.setData(orderDetailResultBean);
        binding.setScoreCode(scoreCode);
        binding.buttonUrge.setVisibility(View.GONE); // 催件
        binding.buttonUrgeDone.setVisibility(View.GONE); // 已催件
        binding.buttonScore.setVisibility(View.GONE); // 评分
        binding.orderGoodsScoreMsg.setVisibility(View.GONE); // 评分提示信息
        String code = orderDetailResultBean.getOrderMain().getOrderCode();
        String goodsState = orderDetailResultBean.getOrderMain().getGoodsState();
        String orderState = "";
        // 0处理中，1已调度，2已到达,3已取货
        switch (goodsState) {
            case "0":
                orderState = getResources().getString(R.string.order_state_0);
                initUrgeOption(code);
                break;
            case "1":
                orderState = getResources().getString(R.string.order_state_1);
                initUrgeOption(code);
                break;
            case "2":
                orderState = getResources().getString(R.string.order_state_2);
                initUrgeOption(code);
                break;
            case "3": {
                orderState = getResources().getString(R.string.order_state_3);
                /**
                 * todo : 取货后，24小时内显示评分，目前根据
                 */
//            评分状态(可评分（code=1）)(已评分（code=2）)(已过期（code=3）)(没权限（code=4）)(不能评（code=5）)
                if ("1".equals(scoreCode)) {
                    binding.orderGoodsScoreMsg.setVisibility(View.VISIBLE);
                    binding.buttonScore.setVisibility(View.VISIBLE);
                } else if ("2".equals(scoreCode)) {

                } else {

                }
                break;
            }
            default:
                break;
        }
        binding.orderGoodsStatus.setText(orderState);
        /**
         * init score
         */
        List<OrderDetailResultBean.OrderScoreBean> orderScores = orderDetailResultBean.getOrderScore();
        if (orderScores != null && orderScores.size() > 0) {
            OrderDetailResultBean.OrderScoreBean orderScoreBean = orderScores.get(0);
            binding.scoreStarts.setRating(6 - orderScoreBean.getScore());
            binding.scoreTime.setText(orderScoreBean.getSubmitTime());
//            <!--1-非常满意，2-比较满意，3-一般，4-不满意 5-非常不满意-->
            switch (orderScoreBean.getScore()) {
                case 1:
                    binding.scoreMessage.setText("非常满意");
                    break;
                case 2:
                    binding.scoreMessage.setText("比较满意");
                    break;
                case 3:
                    binding.scoreMessage.setText("一般");
                    break;
                case 4:
                    binding.scoreMessage.setText("不满意");
                    break;
                case 5:
                    binding.scoreMessage.setText("非常不满意");
                    break;
            }
        }
    }

    @Override
    public void getOrderDetailFailed(String msg) {
        binding.statusLayout.showErrorServerView();
        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                presenter.getOrderDetail(phone, orderCode, scoreCode, userInfo);
            }
        });
        ToastManager.showCenterForShort(msg);
    }

    @Override
    public void getOrderDetailFailed(Throwable e) {
        binding.statusLayout.showErrorNetworkView();
        binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                presenter.getOrderDetail(phone, orderCode, scoreCode, userInfo);
            }
        });
        ToastManager.showCenterForShort(e.getMessage());
    }

    @Override
    public void getDriverInfoSuccess(LogisticsDriverInfoBean logisticsDriverInfoBean) {
        binding.setDirverInfo(logisticsDriverInfoBean);
    }

    @Override
    public void getOrderStatusProgressSuccess(List<OrderStatusBean> orderStatusBeans) {
        this.orderStatusBeans = (ArrayList<OrderStatusBean>) orderStatusBeans;
        Logger.d("111 getOrderStatusProgressSuccess : \n" + GsonUtils.toJsonString(orderStatusBeans, true));
        presenter.handleOrderStatusProgressDataObservable(orderStatusBeans)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<OrderStatusBean>>() {
                    @Override
                    public void accept(List<OrderStatusBean> orderStatusBeans) throws Exception {
                        Logger.d("222 getOrderStatusProgressSuccess : \n" + GsonUtils.toJsonString(orderStatusBeans, true));
                        showOrderStatusProgressRouterBottomSheet((ArrayList<OrderStatusBean>) orderStatusBeans);
                    }
                });
    }

    @Override
    public void getOrderStatusProgressFailed(String msg) {
        ToastManager.showCenterForShort(msg);
    }

    @Override
    public void postOrderUrgeSuccess(LogisticsUrgeResultBean logisticsUrgeResultBean) {
        // 保存当前订单催件时间
        presenter.saveUrgePostTime(orderCode);
        showUrgeSuccessDialog = new MaterialDialog.Builder(OrderDetailActivity.this)
                .customView(R.layout.order_logistics_urge, true)
                .positiveText("知道了")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        /**
                         * todo : 刷新
                         */
                        presenter.refreshOrderDetail(phone, orderCode, scoreCode, userInfo);
                    }
                })
                .positiveColor(getResources().getColor(R.color.purple_0))
                .negativeText("留言")
                .negativeColor(getResources().getColor(R.color.black_666))
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        /**
                         * todo : 催件成功，更新view
                         */
                        showUrgeSuccessDialog.dismiss();
                        showOrderUrgeMessagePostBox();
                    }
                })
                .backgroundColor(getResources().getColor(R.color.window_background))
                .show();
        showUrgeSuccessDialog.setCancelable(false);
    }

    public void showOrderUrgeMessagePostBox() {
        showUrgeMessageDialog = new MaterialDialog.Builder(OrderDetailActivity.this)
                .title("留言")
                .customView(R.layout.order_logistics_urge_message, true)
                .positiveText("确认")
                .positiveColor(getResources().getColor(R.color.purple_0))
                .negativeText("取消")
                .negativeColor(getResources().getColor(R.color.black_666))
                .backgroundColor(getResources().getColor(R.color.window_background))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (TextUtils.isEmpty(urgeMessage)) {
                            ToastManager.showCenterForShort("留言不能为空");
                        } else {
                            presenter.postOrderUrgeMessage(urgeMessage, userInfo, orderDetailResultBean);
                        }
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        showUrgeMessageDialog.dismiss();
                    }
                })
                .dismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (subscribeMessageInput != null && !subscribeMessageInput.isDisposed()) {
                            subscribeMessageInput.dispose();
                            subscribeMessageInput = null;
                        }
                        /**
                         * todo : 刷新
                         */
                        presenter.refreshOrderDetail(phone, orderCode, scoreCode, userInfo);
                    }
                })
                .show();
        showUrgeMessageDialog.setCancelable(false);
        subscribeMessageInput = RxTextView.afterTextChangeEvents(showUrgeMessageDialog.getCustomView().findViewById(R.id.message))
                .subscribe(new Consumer<TextViewAfterTextChangeEvent>() {
                    @Override
                    public void accept(TextViewAfterTextChangeEvent textViewAfterTextChangeEvent) throws Exception {
                        urgeMessage = textViewAfterTextChangeEvent.editable().toString();
                    }
                });
    }

    public void showOrderCancelDialog() {
        showOrderCancelDialog = new MaterialDialog.Builder(OrderDetailActivity.this)
                .title("取消订单")
                .content("确认取消订单?")
                .positiveText("确认")
                .positiveColor(getResources().getColor(R.color.purple_0))
                .negativeText("取消")
                .negativeColor(getResources().getColor(R.color.black_666))
                .backgroundColor(getResources().getColor(R.color.window_background))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        presenter.deleteOrder(phone, orderCode);
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        showOrderCancelDialog.dismiss();
                    }
                })
                .show();
        showOrderCancelDialog.setCancelable(false);
    }

    @Override
    public void postOrderUrgeMessageSuccess() {
        if (showUrgeMessageDialog != null && showUrgeMessageDialog.isShowing()) {
            showUrgeMessageDialog.dismiss();
        }
    }

    @Override
    public void getOrderDeliveryDstance(DstanceBean dstanceBean) {
        binding.setShowMap(true);
        binding.setDstanceBean(dstanceBean);

        LatLng carLatLng = new LatLng(dstanceBean.getCarY(), dstanceBean.getCarX());
        mCustomLatLng = new LatLng(dstanceBean.getCustY(), dstanceBean.getCustX());

        mCarMarker = (Marker) mMap.addOverlay(new MarkerOptions()
                .position(carLatLng)
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.icon_car_location)));

//        View carPopView = View.inflate(this, R.layout.map_marker_pop, null);
//
//        mCarPopMarker = (Marker) mMap.addOverlay(new MarkerOptions()
//                .position(carLatLng)
//                .anchor(0.5f, 1f)
//                .icon(BitmapDescriptorFactory
//                        .fromView(carPopView)));

        Marker csutomMarker = (Marker) mMap.addOverlay(new MarkerOptions()
                .position(mCustomLatLng)
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromBitmap(DrawableUtils.getBitmap(getResources().getDrawable(R.drawable.icon_custom_location)))));

        mPolyline = (Polyline) mMap.addOverlay(new PolylineOptions().width(5)
                .color(getResources().getColor(R.color.black_alpha_35)).points(Arrays.asList(carLatLng, mCustomLatLng)));
        mPolyline.setDottedLine(true);

        MapUtils.zoomToSpan(mMap, false, carLatLng, mCustomLatLng);
        MapUtils.moveCenterPoint(mMap, false, carLatLng, mCustomLatLng);

        presenter.getHistoryTrack(dstanceBean.getTerminalID(), userInfo, orderCode);
    }

    // 更新取件司机提示信息
    @Override
    public void updateOrderDeliveryDstance(DstanceBean dstanceBean) {
        binding.setDstanceBean(dstanceBean);
    }

    @Override
    public void onMoveCar(LatLng latLng) {
        if (mCarMarker != null) {
            mCarMarker.setPosition(latLng);
        }
//        if (mCarPopMarker != null) {
//            mCarPopMarker.setPosition(latLng);
//        }
        mPolyline.setPoints(Arrays.asList(latLng, mCustomLatLng));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_order_detail, menu);
        return true;
    }

    public void showOrderStatusProgressRouterBottomSheet(ArrayList<OrderStatusBean> orderStatusBeans) {
        if (bottomSheet == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(this);
            BottomSheetOrderStatusProgressRouterBinding binding = DataBindingUtil.inflate(layoutInflater, R.layout.bottom_sheet_order_status_progress_router, null, false);
            bottomSheet = new BottomSheet.Builder(this, R.style.order_status_progress_router)
                    .setView(binding.getRoot()).create();
            orderStatusAdapter = new MultiTypeAdapter();
            orderStatusAdapter.setItems(orderStatusBeans);
            orderStatusAdapter.register(OrderStatusBean.class, new OrderStatusRouterViewBinder());
            binding.orderStatusRouter.setLayoutManager(new LinearLayoutManager(this));
            binding.orderStatusRouter.setAdapter(orderStatusAdapter);
            RxView.clicks(binding.close)
                    .compose(new DebounceObservableTransformer<Object>())
                    .subscribe(new Consumer<Object>() {
                        @Override
                        public void accept(Object o) throws Exception {
                            if (bottomSheet != null && bottomSheet.isShowing()) {
                                bottomSheet.dismiss();
                            }
                        }
                    });
        } else {
            orderStatusAdapter.setItems(orderStatusBeans);
            orderStatusAdapter.notifyDataSetChanged();
        }
        bottomSheet.show();
    }

    @Override
    public void deleteOrderSuccess(String s) {
//        ToastManager.show(this, s);
        setResult(Activity.RESULT_OK);
        finish();
    }

    @Override
    public void deleteOrderServerFailed(String msg) {
        ToastManager.show(this, msg);
    }

    @Override
    public void deleteOrderNetFailed(String message) {
        ToastManager.show(this, message);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SCORE: {
                Logger.d("onActivityResult resultCode : " + resultCode);
                if (resultCode == Activity.RESULT_OK) {
                    /**
                     * todo : 完成评分，刷新数据
                     */
//                    binding.statusLayout.showLoadingView();
                    presenter.refreshOrderDetail(phone, orderCode, scoreCode, userInfo);
                }
                break;
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.menu_contact:
                ToastManager.showCenterForShort("联系客服");
                Intent intent = ScoreActivity.newStartIntentForScoreOrder(OrderDetailActivity.this, orderDetailResultBean.getOrderMain().getOrderCode());
                startActivityForResult(intent, REQUEST_CODE_SCORE);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding.mapView.onDestroy();
    }

    @Override
    public void onError() {
    }

    @Override
    public void onError(String msg) {
        ToastManager.showCenterForShort(msg);
    }

    @Override
    public void onLoading() {
        dialog = KyeProgressDialog.show(this, dialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(dialog);
    }
}
